﻿using Abp.Domain.Repositories;
using Abp.UI;
using App.Authorization.Users;
using App.Organizations.Dto;
using Omu.ValueInjecter;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace App.Organizations
{
    public class OrganizationUnitAppService : AppServiceBase, IOrganizationUnitAppService
    {
        private readonly UserManager _userManager;
        private readonly IRepository<OrganizationUnit> _teamRepository;

        public OrganizationUnitAppService(
            UserManager userManager,
            IRepository<OrganizationUnit> teamRepository)
        {
            _userManager = userManager;
            _teamRepository = teamRepository;
        }

        public async Task<List<OrganizationUnit>> GeTeams(Expression<Func<OrganizationUnit, bool>> predicate = null)
        {
            if (predicate == null)
                return await _teamRepository.GetAllListAsync();

            return await _teamRepository.GetAllListAsync(predicate);
        }

        public async Task<OrganizationUnit> CreateTeam(OrganizationUnitDto dto)
        {
            if (await _teamRepository.CountAsync(t => t.TeamName == dto.TeamName) > 0)
            {
                throw new UserFriendlyException(string.Format("名为【{0}】的组织机构已经存在！", dto.TeamName));
            }

            var team = new OrganizationUnit();
            team.InjectFrom(dto);
            team.TenantId = AbpSession.TenantId;

            return await _teamRepository.InsertAsync(team);
        }

        public async Task UpdateTeam(int id, OrganizationUnitDto dto)
        {
            var team = await _teamRepository.FirstOrDefaultAsync(s => s.Id == id);
            if (team == null)
            {
                throw new UserFriendlyException(string.Format("找不到该记录Team Id为{0}的记录", id));
            }

            team.InjectFrom(dto);
        }

        public async Task DeleteAsync(int id)
        {
            await _teamRepository.DeleteAsync(id);
        }
    }
}
